<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增客户审批流程"
    width="800px"
    @close="handleClose"
  >
    <div v-loading="loading" class="approval-process">
      <!-- 流程步骤 -->
      <div class="process-steps">
        <el-steps :active="currentStepIndex" finish-status="success" align-center>
          <el-step
            v-for="(step, index) in processSteps"
            :key="index"
            :title="step.name"
            :status="getStepStatus(step, index)"
            :description="step.description"
          >
            <template #icon>
              <el-icon v-if="step.status === 'completed'">
                <Check />
              </el-icon>
              <el-icon v-else-if="step.status === 'rejected'">
                <Close />
              </el-icon>
              <el-icon v-else-if="step.status === 'current'">
                <Loading />
              </el-icon>
              <el-icon v-else>
                <Clock />
              </el-icon>
            </template>
          </el-step>
        </el-steps>
      </div>

      <!-- 流程详情 -->
      <div class="process-details" v-if="processInfo">
        <el-card shadow="never">
          <template #header>
            <div class="card-title">
              <el-icon><Operation /></el-icon>
              流程信息
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label>流程实例ID：</label>
                <span>{{ processInfo.processInstanceId }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label>流程状态：</label>
                <el-tag :type="getStatusType(processInfo.processStatus)">
                  {{ getStatusText(processInfo.processStatus) }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label>当前步骤：</label>
                <span>{{ processInfo.currentStep || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label>当前审批人：</label>
                <span>{{ processInfo.currentApprover || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 审批历史 -->
      <div class="approval-history" v-if="approvalSteps.length > 0">
        <el-card shadow="never">
          <template #header>
            <div class="card-title">
              <el-icon><Document /></el-icon>
              审批历史
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="(step, index) in approvalSteps"
              :key="index"
              :timestamp="formatDate(step.endTime)"
              :type="getTimelineType(step.result)"
            >
              <el-card>
                <div class="timeline-content">
                  <div class="step-header">
                    <span class="step-name">{{ step.taskName }}</span>
                    <el-tag :type="getResultType(step.result)" size="small">
                      {{ getResultText(step.result) }}
                    </el-tag>
                  </div>
                  <div class="step-details">
                    <p><strong>审批人：</strong>{{ step.assignee }}</p>
                    <p v-if="step.comment"><strong>审批意见：</strong>{{ step.comment }}</p>
                    <p v-if="step.result === 'REJECTED' && step.comment">
                      <strong>拒绝原因：</strong>
                      <span class="reject-reason">{{ step.comment }}</span>
                    </p>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>

      <!-- 审批操作 -->
      <div class="approval-actions" v-if="canApprove">
        <el-card shadow="never">
          <template #header>
            <div class="card-title">
              <el-icon><User /></el-icon>
              审批操作
            </div>
          </template>
          
          <div class="action-buttons">
            <el-button type="success" @click="handleApprove">
              <el-icon><Check /></el-icon>
              通过
            </el-button>
            <el-button type="danger" @click="handleReject">
              <el-icon><Close /></el-icon>
              拒绝
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Check, Close, Loading, Clock, Operation, Document, User 
} from '@element-plus/icons-vue'
import { getCustomerProcess, getCustomerProcessSteps, approveCustomer } from '../../api/customer.js'

export default {
  name: 'CustomerApprovalProcess',
  components: {
    Check, Close, Loading, Clock, Operation, Document, User
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    customer: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'approve', 'reject'],
  setup(props, { emit }) {
    const dialogVisible = computed(() => props.visible)
    const loading = ref(false)
    const processInfo = ref(null)
    const approvalSteps = ref([])
    
    // 监听对话框显示状态
    watch(() => props.visible, async (visible) => {
      if (visible && props.customer?.id) {
        await loadProcessData()
      }
    })
    
    // 加载流程数据
    const loadProcessData = async () => {
      if (!props.customer?.id) return
      
      try {
        loading.value = true
        
        // 加载流程信息
        const processResponse = await getCustomerProcess(props.customer.id)
        processInfo.value = processResponse
        
        // 如果有流程实例ID，加载流程步骤
        if (processResponse?.processInstanceId) {
          const stepsResponse = await getCustomerProcessSteps(processResponse.processInstanceId)
          approvalSteps.value = stepsResponse || []
        }
      } catch (error) {
        console.error('加载流程数据失败:', error)
        ElMessage.error('加载流程数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 流程步骤 - 根据真实BPMN流程定义
    const processSteps = computed(() => {
      const steps = [
        { name: '销售员填写客户资料', description: '销售员填写客户资料', taskId: 'taskFillInfo' },
        { name: '地区经理审批', description: '地区经理审批', taskId: 'taskManagerApprove' },
        { name: '大区经理审批', description: '大区经理审批', taskId: 'taskDirectorApprove' },
        { name: '信用控制组审批', description: '信用控制组审批', taskId: 'taskCreditControl' },
        { name: '销售总监审批', description: '销售总监审批', taskId: 'taskSalesDirector' },
        { name: '公司商务人员审核', description: '公司商务人员审核', taskId: 'taskBusinessConfirm' }
      ]
      
      if (!processInfo.value) return steps
      
      const currentStep = processInfo.value.currentStep
      const status = processInfo.value.processStatus
      
      // 根据审批历史确定步骤状态
      if (approvalSteps.value.length > 0) {
        const completedSteps = approvalSteps.value.filter(step => step.status === 'COMPLETED')
        const rejectedStep = approvalSteps.value.find(step => step.result === 'REJECTED')
        
        steps.forEach((step, index) => {
          if (rejectedStep && step.name === rejectedStep.taskName) {
            step.status = 'rejected'
          } else if (completedSteps.some(completed => completed.taskName === step.name)) {
            step.status = 'completed'
          } else if (step.name === currentStep) {
            step.status = 'current'
          } else {
            step.status = 'pending'
          }
        })
      } else {
        // 没有审批历史时的默认状态
        if (status === 'APPROVED') {
          steps.forEach(step => step.status = 'completed')
        } else if (status === 'REJECTED') {
          // 根据拒绝原因确定在哪个步骤被拒绝
          const rejectedIndex = steps.findIndex(step => step.name === currentStep)
          if (rejectedIndex >= 0) {
            steps[rejectedIndex].status = 'rejected'
          } else {
            steps[0].status = 'rejected'
          }
        } else if (currentStep) {
          const currentIndex = steps.findIndex(step => step.name === currentStep)
          for (let i = 0; i < currentIndex; i++) {
            steps[i].status = 'completed'
          }
          if (currentIndex >= 0) {
            steps[currentIndex].status = 'current'
          }
        } else if (status === 'PENDING') {
          // 待审批状态，第一个步骤为当前步骤
          steps[0].status = 'current'
        }
      }
      
      return steps
    })
    
    // 当前步骤索引
    const currentStepIndex = computed(() => {
      const currentStep = processInfo.value?.currentStep
      if (!currentStep) return 0
      
      const index = processSteps.value.findIndex(step => step.name === currentStep)
      return index >= 0 ? index : 0
    })
    
    // 是否可以审批
    const canApprove = computed(() => {
      if (!processInfo.value) return false
      
      const status = processInfo.value.processStatus
      const currentApprover = processInfo.value.currentApprover
      
      // 只有审批中状态且当前用户是审批人时才能审批
      return status === 'APPROVING' && currentApprover === getCurrentUser()
    })
    
    // 获取当前用户
    const getCurrentUser = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr)
        return userInfo.username
      }
      return null
    }
    
    // 获取步骤状态
    const getStepStatus = (step, index) => {
      if (step.status === 'completed') return 'success'
      if (step.status === 'rejected') return 'error'
      if (step.status === 'current') return 'process'
      return 'wait'
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVING': 'primary',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVING': '审批中',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 获取时间线类型
    const getTimelineType = (result) => {
      if (result === 'APPROVED') return 'success'
      if (result === 'REJECTED') return 'danger'
      return 'primary'
    }
    
    // 获取结果类型
    const getResultType = (result) => {
      if (result === 'APPROVED') return 'success'
      if (result === 'REJECTED') return 'danger'
      return 'info'
    }
    
    // 获取结果文本
    const getResultText = (result) => {
      if (result === 'APPROVED') return '通过'
      if (result === 'REJECTED') return '拒绝'
      return '待处理'
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString()
    }
    
    // 处理审批
    const handleApprove = async () => {
      try {
        loading.value = true
        
        // 获取当前任务ID（这里需要从流程信息中获取）
        const currentTaskId = processInfo.value?.currentTaskId
        if (!currentTaskId) {
          ElMessage.error('无法获取当前任务信息')
          return
        }
        
        // 调用审批API
        await approveCustomer({
          customerId: props.customer.id,
          taskId: currentTaskId,
          approvalResult: 'APPROVED',
          approvalComment: '审批通过',
          approverId: getCurrentUser(),
          approverName: getCurrentUser(),
          approverRole: 'APPROVER',
          approvalStep: processInfo.value?.currentStep || '审批'
        })
        
        ElMessage.success('审批通过成功')
        emit('approve')
        
        // 重新加载流程数据
        await loadProcessData()
        
      } catch (error) {
        console.error('审批失败:', error)
        ElMessage.error('审批操作失败')
      } finally {
        loading.value = false
      }
    }
    
    // 处理拒绝
    const handleReject = () => {
      // 显示拒绝原因输入对话框
      ElMessageBox.prompt('请输入拒绝原因', '审批拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入拒绝原因...'
      }).then(async ({ value }) => {
        if (!value || value.trim() === '') {
          ElMessage.warning('请输入拒绝原因')
          return
        }
        
        try {
          loading.value = true
          
          // 获取当前任务ID
          const currentTaskId = processInfo.value?.currentTaskId
          if (!currentTaskId) {
            ElMessage.error('无法获取当前任务信息')
            return
          }
          
          // 调用审批API
          await approveCustomer({
            customerId: props.customer.id,
            taskId: currentTaskId,
            approvalResult: 'REJECTED',
            approvalComment: value.trim(),
            approverId: getCurrentUser(),
            approverName: getCurrentUser(),
            approverRole: 'APPROVER',
            approvalStep: processInfo.value?.currentStep || '审批'
          })
          
          ElMessage.success('审批拒绝成功')
          emit('reject')
          
          // 重新加载流程数据
          await loadProcessData()
          
        } catch (error) {
          console.error('审批拒绝失败:', error)
          ElMessage.error('审批拒绝失败')
        } finally {
          loading.value = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    }
    
    // 关闭对话框
    const handleClose = () => {
      emit('update:visible', false)
    }
    
    return {
      dialogVisible,
      loading,
      processInfo,
      approvalSteps,
      processSteps,
      currentStepIndex,
      canApprove,
      getStepStatus,
      getStatusType,
      getStatusText,
      getTimelineType,
      getResultType,
      getResultText,
      formatDate,
      handleApprove,
      handleReject,
      handleClose
    }
  }
}
</script>

<style scoped>
.approval-process {
  max-height: 70vh;
  overflow-y: auto;
}

.process-steps {
  margin-bottom: 30px;
}

.process-details,
.approval-history,
.approval-actions {
  margin-bottom: 20px;
}

.card-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.card-title .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: 600;
  color: #606266;
  min-width: 120px;
  margin-right: 10px;
}

.detail-item span {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

.timeline-content {
  padding: 10px 0;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.step-name {
  font-weight: 600;
  color: #303133;
}

.step-details p {
  margin: 5px 0;
  color: #606266;
}

.reject-reason {
  color: #F56C6C;
  font-style: italic;
}

.action-buttons {
  text-align: center;
  padding: 20px 0;
}

.action-buttons .el-button {
  margin: 0 10px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>
